package com.pet.shop.service.user;

import com.github.pagehelper.Page;
import com.pet.exceptions.BusinessException;
import com.pet.shop.dto.PageDto;
import com.pet.shop.entity.user.UserInfo;
import com.pet.shop.mappers.user.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserInfoServiceImpl implements IUserInfoService{

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public int deleteEntity(Long id) {
        return userInfoMapper.delete(id);
    }

    @Override
    public int deleteEntityList(List<Long> idList) {
        if(idList == null || idList.isEmpty()) return 0;
        int i = 0;
        for (Long id : idList) {
            i += userInfoMapper.delete(id);
        }
        return i;
    }

    @Override
    public UserInfo insertEntity(UserInfo record) {
        if(StringUtils.isEmpty(record.getOpenid())){
            throw new BusinessException("必须通过微信小程序注册");
        }
        UserInfo serverUser = userInfoMapper.queryByOpenid(record.getOpenid());
        if(serverUser != null){
            record.setId(serverUser.getId());
            userInfoMapper.update(record);
            record = userInfoMapper.get(serverUser.getId());
        }else{
            userInfoMapper.insert(record);
        }

        return record;
    }

    @Override
    public UserInfo getEntity(Long id) {
        return userInfoMapper.get(id);
    }

    @Override
    public int updateEntity(UserInfo record) {
        return userInfoMapper.update(record);
    }

    @Override
    public PageDto<UserInfo> queryPage(PageDto<UserInfo> pageDto) {
        Page<UserInfo> page =  userInfoMapper.queryPage(pageDto);
        pageDto.setPageResult(page);
        return pageDto;
    }
}
